var Md5 = require('../utils/md5.js');
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};
const formatdate = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    return [year, month].map(formatNumber).join('-')
};
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
};
function http(url, data, callback) {
    data.key = "bdf8894461d820f0f068e07e1befb737";
    data.timestamp = Date.parse(new Date()) / 1000;
    var sign = Md5.hexMD5(data.timestamp + 'iqidian' + data.key); //md5加密
    data.sign = sign;
    if (data.goods_list !== undefined) {
        data.goods_list = JSON.stringify(data.goods_list);
    }
    wx.request({
        url: getApp().globalData.http + url,
        data: data,
        header: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        dataType: "json",
        success: function(res) {
            callback(res.data)
        },
        fail: function(res) {},
        complete: function(res) {},
    })
};

function message(msg) {
    wx.showModal({
        title: '温馨提示',
        content: msg,
        showCancel: false,
        success(res) {}
    })
}

function showLoading(msg) {
    wx.showLoading({
        mask: true,
        title: msg ? msg : '加载中',
    })
}

function hideLoading() {
    wx.hideLoading();
}

function in_array(search, array) {
    for (var i in array) {
        if (array[i]['id'] == search) {
            return true;
        }
    }
    return false;
}
//数据去重
function uniqueSearchRecord(newRecord) {
    var that = this;
    var listInfo = [];
    //加入缓存
    listInfo.push(newRecord);
    var listPost = wx.getStorageSync("listPost") || [];
    for (var i = 0; i < listPost.length; i++) {
        //如果当前数组的第i个已经保存进了临时数组，那么跳过，否者吧当前项push到临时数组里面
        if (!in_array(listPost[i]['id'], listInfo) && listPost[i].id !== newRecord && newRecord !== '' && newRecord !== null && newRecord !== undefined) {
            listInfo.push(listPost[i]);
        } else {
            listInfo[0].number = parseInt(listPost[i].number) + 1;
        }
    }
    wx.setStorageSync("listPost", listInfo);
}
module.exports = {
    formatTime: formatTime,
    formatdate: formatdate,
    showLoading: showLoading,
    hideLoading: hideLoading,
    message: message,
    http: http,
    uniqueSearchRecord: uniqueSearchRecord
}